var b = {}
$(function(){
	b.nk = getCookie("b_nk_");
	if(b.nk){
		$("#b_nk").html("<a href='/profile.html'>个人主页</a> <a href='/setting.html'>设置</a> <a href='javascript:;' onclick='b.user.logout();'>退出</a>");
	}
	$(".click").inputText();//form input css style when on focusin and focusout
});
b.user = {
	register:function(){
		var txt = '<form action="/auth/login" method="post" onsubmit="return false;" id="box-lf" accept-charset="utf-8" class="nz-box">'+
					'<h1>注册</h1>'+
					'<div class="b-l-i">'+
						'<label for="login">邮箱</label>'+
						'<input type="text" name="login" id="login" value="" />'+
						'<span class="b-l-error" id="p-login-e"></span>'+
					'</div>'+
					'<div class="b-l-i">'+
						'<label for="password">密码</label>'+
						'<input type="password" name="password" id="password" value="" />'+
						'<span class="b-l-error" id="p-login-p"></span>'+
					'</div>'+
					'<div class="b-su">'+
						'<input type="submit" class="button" id="submit" value="注册">'+
					'</div>'+
				'</form>';
		$.colorbox({
			'html':txt,
			'width':400,
			'height':270,
			'opacity':0.3,
			'transition':'none',
			'fixed':true,
			'onComplete':function(){
				var $submit = true;
				var $e = $("#login"); var $p = $("#password");
				var $ep = $("#p-login-e");
				var $epp = $("#p-login-p");
				$e[0].focus();
				$e.bind({"focusin":function(){$("#p-login-e").html("").hide();},"focusout":function(){
					var e = $e.val();
					if(!e.length){
						$ep.html("邮箱不能为空").show();
						$submit = false;
						return;
					}else $submit = true;
					if(!(/^[_a-z0-9]+@([_a-z0-9]+\.)+[a-z0-9]{2,3}$/).test(e)){
						$ep.html("邮箱格式不正确").show();
						$submit = false;
						return;
					}else $submit = true;
					if(e.length > 30 || e.length < 6){
						$ep.html("邮箱必须大于6位小于30位").show();
						$submit = false;
						return;
					}else $submit = true;
				}});
				$p.bind({"focusin":function(){$("#p-login-p").html("").hide();},"focusout":function(){
					var p = $p.val();
					if(!p.length){
						$epp.html("密码不能为空").show();
						$submit = false;
						return;
					}else $submit = true;
					if(p.length > 20 || p.length < 6){
						$epp.html("密码必须大于6位小于20位").show();
						$submit = false;
						return;
					}else $submit = true;
				}});
				$("#box-lf").bind("submit", function(e){
					if(!$submit) return;
					var e = $e.val();
					var p = $p.val();
					var d = {'mail':encodeURI(e),'password':encodeURI(p)};
					$.ajax({
						'url':'/rest/user/reg',
						'type':'post',
						'data':d,
						'dataType':'json',
						'success':function(d,t,j){
							if(d.result){
								$.colorbox.close();
							}else{
								$ep.html(b.error[d.error]).show();
							}
						},
						'error':function(j,t,e){
							
						}
					});
					return false;
				});
			}
		});
	},
	login:function(){
		var txt = '<form action="/auth/login" method="post" onsubmit="return false;" id="box-lf" accept-charset="utf-8" class="nz-box">'+
					'<h1>登录</h1>'+
					'<div class="b-l-i">'+
						'<label for="login">邮箱</label>'+
						'<input type="text" name="login" id="login" value="" />'+
						'<span class="b-l-error" id="p-login-e"></span>'+
					'</div>'+
					'<div class="b-l-i">'+
						'<label for="password">密码</label>'+
						'<input type="password" name="password" id="password" value="" />'+
						'<span class="b-l-error" id="p-login-p"></span>'+
					'</div>'+
					'<div class="b-su">'+
						'<input type="submit" class="button" id="submit" value="登录">'+
					'</div>'+
				'</form>';
		$.colorbox({
			'html':txt,
			'width':400,
			'height':270,
			'opacity':0.3,
			'transition':'none',
			'fixed':true,
			'onComplete':function(){
				var $submit = true;
				var $e = $("#login"); var $p = $("#password");
				var $ep = $("#p-login-e");
				var $epp = $("#p-login-p");
				$e[0].focus();
				$e.bind({"focusin":function(){$("#p-login-e").html("").hide();},"focusout":function(){
					var e = $e.val();
					if(!e.length){
						$ep.html("邮箱不能为空").show();
						$submit = false;
						return;
					}else $submit = true;
					if(!(/^[_a-z0-9]+@([_a-z0-9]+\.)+[a-z0-9]{2,3}$/).test(e)){
						$ep.html("邮箱格式不正确").show();
						$submit = false;
						return;
					}else $submit = true;
					if(e.length > 30 || e.length < 6){
						$ep.html("邮箱必须大于6位小于30位").show();
						$submit = false;
						return;
					}else $submit = true;
				}});
				$p.bind({"focusin":function(){$("#p-login-p").html("").hide();},"focusout":function(){
					var p = $p.val();
					if(!p.length){
						$epp.html("密码不能为空").show();
						$submit = false;
						return;
					}else $submit = true;
					if(p.length > 20 || p.length < 6){
						$epp.html("密码必须大于6位小于20位").show();
						$submit = false;
						return;
					}else $submit = true;
				}});
				$("#box-lf").bind("submit", function(e){
					if(!$submit) return;
					var e = $e.val();
					var p = $p.val();
					var d = {'mail':encodeURI(e),'password':encodeURI(p)};
					$.ajax({
						'url':'/rest/user/mailLogin',
						'type':'post',
						'data':d,
						'dataType':'json',
						'success':function(d,t,j){
							if(d.result){
								$.colorbox.close();
								//写入cookie
								var bnk = e.split("@");
								setCookie("b_nk_",bnk[0]);
								setCookie("b_nk_id",d.id);
								window.location.href= '/setting.html';
							}else{
								$ep.html(b.error[d.error]).show();
							}
						},
						'error':function(j,t,e){
							
						}
					});
					return false;
				});
			}
		});
	},
	logout:function(){
		delCookie("b_nk_");
		delCookie("b_nk_id");
		window.location.href = '/index.html';
	}
}
b.info = function(txt){
	$.colorbox({
		'html':txt,
		'width':500,
		'height':300,
		'opacity':0.9,
		'transition':'none',
		'fixed':true,
		'onComplete':function(){
			window.setTimeout(function(){$.colorbox.close()},1500);
		}
	});
}

b.error = {
	1:'未定义的的API',
	2:'user下中未定义此方法',
	3:'user.creat传入参数不正确',
	4:'注册失败，可能已有相同邮箱已存在',
	5:'user.checkMail传入参数不正确',
	6:'登陆失败，请检查登陆邮箱和密码',
	7:'user.login传入参数不正确',
	8:'请先登陆',
	9:'user.setAccount传入参数不正确',
	10:'已存在相同账号，请换一个',
	11:'user.accountLogin传入参数不正确',
	12:'登陆失败，请检查登陆账号和密码',
	13:'传入参数不正确',
	14:'图书收录失败，请核对编码',
	15:'调用搜索失败，请检查搜索词和搜索类型',
	16:'book下中未定义此方法',
	17:'不存在该id的图书',
	18:'列出图书失败',
	19:'store下中未定义此方法',
	20:'不能操作别人的图书库存',
	21:'该图书库存不存在',
	22:'不能操作别人的共享条目',
	23:'confirmShare的confirm必须为0,1,2其中一个值',
	24:'用户未登陆，注销失败',
	25:'用户处于离线状态',
	26:'修改密码失败',
	27:'用户未作修改',
	28: '该图书没有库存',
	29: '该用户暂没有收录图书',
	30: '该ID用户不存在',
	31: '该图书不可操作'
};
//写cookies函数
function setCookie(name,value)//两个参数，一个是cookie的名子，一个是值
{
    var Days = 30; //此 cookie 将被保存 30 天
    var exp  = new Date();    //new Date("December 31, 9998");
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)//取cookies函数        
{
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
     if(arr != null) return unescape(arr[2]); return null;

}
function delCookie(name)//删除cookie
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
//======================= 输入框绑定插件 =============================================//
$.fn.inputText = function(){
	return this.each(function(){
		var $this = $(this);
		var f = true;
		if($this.hasClass('no-div')){
			f = false;
		}
		var oldVal = $this.val();
		if(oldVal){
			this.style.color="#ADADAD";
			$this.bind("focusin",function(){
				var newVal = this.value;
				if(f){$this.parent("div").removeClass("i-off").addClass("i-on");}
				if(newVal==oldVal){this.value='';this.style.color="#222";}else{$this.select();}
			}).bind("focusout",function(){
				
				var newVal = this.value;
				if(!newVal){this.value=oldVal;this.style.color="#ADADAD";if(f){$this.parent("div").removeClass("i-on").addClass("i-off");}}
			});
		}else{
			$this.bind("focusin",function(){
				if(f){$this.parent("div").removeClass("i-off").addClass("i-on");}
				this.style.color="#222";
			})
		}
	});
}

function search(){
	var k = $("#keyword").val();
	if(k){
		$("#s-a").html("搜索“"+k+"”的结果");
		$.ajax({
				'url':'/rest/book/search',
				'type':'post',
				'data':{"key":encodeURI(k),"type":1},
				'dataType':'json',
				'success':function(d,t,j){
					if(d.result){
						var h = '';
						$.each(d.content.content,function(i,item){
							h += '<div class="s-item clearfix" onclick="b.book.view('+item.doubanID+')"><img src="'+item.img+'" width="80" height="120" /><h1 style="padding-top:20px;">'+item.title+'</h1><p>作者：'+item.author+'</p><p>出版社：'+item.publisher+'</p><p>出版日期：'+item.pubdate+'</p></div>';
						});
						$("#s-item").html(h);
						
						//one book
						$.ajax({
							'url':'/rest/book/catch',
							'type':'post',
							'data':{"id":d.content.content[0].doubanID,"type":1},
							'dataType':'json',
							'success':function(d,t,j){
								if(d.id){
									var id = d.id;
									$.ajax({
										'url':'/rest/book/view',
										'type':'post',
										'data':{"id":id,"type":1},
										'dataType':'json',
										'success':function(d,t,j){
											if(d.result){
												try{$("#s-view-result").remove();}catch(e){}
												var hh = '<div class="r-content clearfix" id="s-view-result"><div class="meta"><img src="'+d.content.image_url+'" height="210" width="140"/><h1 style="padding-top:10px;">'+d.content.title+'</h1><p>作者：'+d.content.author+'</p><p>译者：'+d.content.translator+'</p><p>出版社：'+d.content.publisher+'</p><p>ISBN：'+d.content.isbn10+'</p><p>出版日期：'+d.content.pubdate+'</p><p>价格：'+d.content.price+'</p><p>装帧：'+d.content.binding+'</p><p>页数：'+d.content.pages+'</p></div><div id="s-do"><a href="javascript:" id="s-doh">我有书</a><a href="javascript:" id="s-don">我没书</a></div><div class="clear"></div><h2>图书简介</h2><p class="desc">'
														+d.content.summary+'</p><a href="" class="go-douban">在豆瓣上查看此书详情</a></div>';
												$("#s-view").append(hh);
											}else{
												alert(b.error[d.error]);
											}
										},
										'error':function(j,t,e){
											
										}
									});
								}else{
									alert('ss');
									alert(b.error[d.error]);
								}
							},
							'error':function(j,t,e){
								
							}
						});
					}else{
						alert(b.error[d.error]);
					}
				},
				'error':function(j,t,e){
					
				}
			});
	}
}
b.book = {}
b.book.view = function(doubanID){
	//one book
		$.ajax({
			'url':'/rest/book/catch',
			'type':'post',
			'data':{"id":doubanID,"type":1},
			'dataType':'json',
			'success':function(d,t,j){
				if(d.id){
					var id = d.id;
					$.ajax({
						'url':'/rest/book/view',
						'type':'post',
						'data':{"id":id,"type":1},
						'dataType':'json',
						'success':function(d,t,j){
							if(d.result){
								try{$("#s-view-result").remove();}catch(e){}
								var hh = '<div class="r-content clearfix" id="s-view-result"><div class="meta"><img src="'+d.content.image_url+'" height="210" width="140"/><h1 style="padding-top:10px;">'+d.content.title+'</h1><p>作者：'+d.content.author+'</p><p>译者：'+d.content.translator+'</p><p>出版社：'+d.content.publisher+'</p><p>ISBN：'+d.content.isbn10+'</p><p>出版日期：'+d.content.pubdate+'</p><p>价格：'+d.content.price+'</p><p>装帧：'+d.content.binding+'</p><p>页数：'+d.content.pages+'</p></div><div id="s-do"><a href="javascript:" id="s-doh">我有书</a><a href="javascript:" id="s-don">我没书</a></div><div class="clear"></div><h2>图书简介</h2><p class="desc">'
										+d.content.summary+'</p><a href="" class="go-douban">在豆瓣上查看此书详情</a></div>';
								$("#s-view").append(hh);
							}else{
								alert(b.error[d.error]);
							}
						},
						'error':function(j,t,e){
							
						}
					});
				}else{
					alert('ss');
					alert(b.error[d.error]);
				}
			},
			'error':function(j,t,e){
				
			}
		});
}